import fetch from 'isomorphic-fetch'
import {
	pushInQueue
} from '../message/action.js'
// 成功拉取数据
// state init:
// {
// 		isFetching:false
// 		didInvalidate:false
// 		receivedAt:time
// 		lastUpdate:timestamp
// 		items:[
// 			id:num
// 			title:string
// 			content:string
// 		]
// }
const receiveData = (data) => {
	return {
		type: "RECEIVE_LISTS_DATA",
		isFetching: false,
		items: data,
		receiveAt: Date.now()
	}
}

const receivePageData = (data) => {
	return {
		type: "RECEIVE_PAGE_DATA",
		isFetching: false,
		items: data,
		receiveAt: Date.now()
	}
}

export const fetchArticle = () => {
	return (dispatch) => {
		fetch(__API__.articleAll, {
			method: "GET",
			credentials: 'include'
		}).then(data => data.json()).then(data => {
			console.log(data)
			if (data.error) {
				dispatch(pushInQueue({
					info: "No Access",
					flag: "hint"
				}))
			}
			dispatch(receiveData(data))
		}).catch(err => {
			console.log("error")
			dispatch(pushInQueue({
				info: "Place check your Internet",
				flag: "warning"
			}))
		})
	}
}

export const fetchArticleByPage = (pageId = 0) => {
	console.log(__API__.articlePage + pageId)
	return dispatch => fetch(__API__.articlePage + pageId, {
		method: "GET"
	}).then(data => data.json()).then(data => {
		console.log(data)
		if (data.length != 0) {
			dispatch(receivePageData(data))
		}
	}).catch(err => {
		console.log("err")
	})
}